package com.example.uitl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import org.springframework.stereotype.Component;

@Component
public class PayUtil {
    //个人appid，
    private final String APP_ID = "9021000150600250";
    //编码格式
    private final String CHARSET = "UTF-8";
    //秘钥生成工具生成的 应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDX+rcPo4Nasdh7Cst8DsB2obfBtve8gqdK9umIDlVis956Wv0Y94eDbHhJdGa+K8xN0XLSMyJhhdBPWHAI5zRcu5VPF+x/uitlPQXPNL/rU5YK8jqXVAQ6QZQrVkWEyk8WsprHLT8Z6BF4J/9qTjLRmxW0lo/uS/bmA89V4jKKl2LOPP1q1sDJv9vMdIt4glfyS3Ef7c+CMuPlZrAIZYKsCzYFZ3m5H4/AIqEa4MDs8BK5hUlBVYrzDHg8TA6JomK9QrpZlsdVu8f+xCFOIQJ76x2BLds20N/5V5mEbWWdNeMKDlVO5s6IcBzlI/moW9EKHJNquNNBXVi/zskz2CPJAgMBAAECggEACLXIui2692Zit5uY1zj1FBOziHFrjkOqoYBRrLX/RYrBdyfCO0aIRYmTVEsIdbToeV7wBYAga9RssTZ81i8U0oSSIe1yETid1Whfmpqi/seRLoHUURQHU54fbpv9E7zg8aZkTZIKkG3mfnUGfPAIZqGdf3nu9gpEO8R9kRYdOa+MSjCPWnsnfS7s3kTHKt1fdH3c7I9oJNp5QpmeWqmBElVJU4gmrj4gitDxV3N5Xp1PDV7FuTvFzeFSseoVrm/7ebOCf0yQcUU1+HhhA20aSSgjDOCnpj8IJSsSGMkeF27Oi1QaEm/RUJGiWdJQ8Jmv5L+J+O0kHPo94eyT8iU1gQKBgQDshymehRuMxAqpjF/cgTfvmax8w95aFCVJEtZCFZT5ZdG0IXLd4TwTcp7nlLpf+nA1g+5KAdDhY4pvbMMeA05QksCjkdBdrQsIr+o+HtvR23lvigpayuZyEXJ5Chr43QxxFCSrdSKMGAQtgzmZvyKU+FLHxXokfriSpo0Gu19GMQKBgQDpwn1IUzr2xjmAZbJUJXC7qJieTqlltqNWuRoSSsbgRR/fYKoaZpTbOxByS0bw30FsAvMBL0tqJrGJatJ+ws0naLGH7lG4zy1h3o6Upn5Epsu9K8MTRTPoafTjqfTGAHyNjW98FKsA0+bCyGzeIJEJ2qIcMAihk3BKGi5Nr0eZGQKBgQCg+qz80qMZfyOymXN05A1p6TFYCQcAT83Ami1w9LdbtkyvSEShdnYo1k4IV1UxlYVhJtW7UNkVTWYex+tUNfPLKtYpfUhPOULVOsU2WlJJ1hIkM9MwT//firhaYOJSlj+thoQena5RotbVEwbU+R1UPl440NJ8nDKKvQgmmMgTQQKBgCgzqaYxojdkmekKFGRCWCP999lp/9odUfQNO32f3JofaT7aega2U61seASgC6BLVQ4FZ9NxVc/4vZm7hF4GlI/NgpK1GtrkzpJBW1YXWCnoYau0BgWfZjD3YAVzakRPOxyBEYZOa6Zlyw7+tzJweWEvd6fPXvyixbII1KPJnE+pAoGAeRiE9HnHaaAWMC0Pg5K3J1VUHL/W5oA16pwVMvK9NXeJVWEOIyu7lQTU+UKKAVvFSav1yLY/OdkiO7O/URS7WI0iKniTNuJpHBWKOhJu4rwcJEGUlXlWaiKXA73Oyjb97UjozJVHEcMuJhgFAUflArtj7Z0sH+p4dqsohKg6PAk=";
    // 支付宝公钥，这是在沙箱应用-接口加签方式-自定义秘钥-  添加应用公钥以后生成的支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsfoBy7NOBtoI6SC4ZLDLrPPSl+Fl/Y1J5JSAT1WHsBxpLvSas3dc0b4vfxbtspEzcESOtkSDevKxFDVpj6NNQqsg/Vdh8Az6n9oHK1USYihOT2An0ZwhIC/vUArT0FFl2Ydh28rIu3uBfW42v4rKvHsg7RrTUb8lsv23ZZtlu3BcnBkoklPzrnti+hM5tUNL7mIbRg3AS8MdHNsqx35U2qIEm2ECu9tgHoFFaRrcXhkX22/g69w44iATN6dcreew64m3lPVGtsKgGDDWp7mtg5BxdrFwKM/KCj0nI9x1Beasm4kES5Wa36Mc2dmyuKSSmbDiGyQHc6R59+6wVz5TFwIDAQAB";
    // 支付宝网关地址，沙箱应用页面可直接查看
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    // 请求格式
    private final String FORMAT = "JSON";
    // 加密算法
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会先异步调用本方法,必须为公网地址,优先在这里做业务逻辑处理
    //但是由于这里需要外网，我们在本地测试可以使用内网穿透的方式模拟公网ip请求
    // api/alipay/notify自己在项目中的实现类接口
    private final String NOTIFY_URL = "http://g6c67962.natappfree.cc/LangBridge_war_exploded/api/alipay/notify";
    //支付宝同步通知路径,也就是当付款完毕后，可以自定义跳转本项目的自定义页面,可以不是公网地址,可以调到我的订单页面
    //api/alipay/return这个也是实现类中的接口
    private final String RETURN_URL = "http://localhost:8080/LangBridge_war_exploded/api/alipay/return";

    private AlipayClient alipayClient = null;
    /**
     * 向支付宝发送支付请求
     *
     * @param outTradeNo  商户订单号
     * @param totalAmount 订单总金额
     * @param subject     订单标题
     */
    public String sendRequestToAlipay(String outTradeNo, Float totalAmount, String subject) throws AlipayApiException {
        // 初始化AlipayClient，配置支付宝网关、应用ID、私钥等参数
        alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        // 创建支付宝支付请求对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 设置异步回调地址（支付宝服务器异步通知商户服务器的地址）
        alipayRequest.setNotifyUrl(NOTIFY_URL);
        // 设置同步回调地址（用户付款后跳转的页面）
        alipayRequest.setReturnUrl(RETURN_URL);
        //商品描述（可空）
        String body = "";
        // 构建业务参数JSON对象
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("total_amount", totalAmount);
        bizContent.put("subject", subject);
        bizContent.put("body", body);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(bizContent.toJSONString()); // 注意使用toJSONString()
        // 执行支付请求并获取返回结果
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("返回的结果："+result );
        return result;
    }

    /**
     * 查询指定订单的信息
     *
     * @param id 订单编号
     * @return 支付查询结果的原始响应体
     */
    public String query(String id){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        // 构建业务参数JSON对象
        JSONObject bizContent = new JSONObject();
        // 商户订单号
        bizContent.put("out_trade_no", id);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        String body=null;
        try {
            // 执行查询请求并获取响应
            response = alipayClient.execute(request);
            body = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return body;
    }
}
